package com.jerry.huihome.module.home.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioGroup;

import com.jerry.huihome.R;
import com.jerry.huihome.module.home.adapter.GuidePageAdapter;
import com.jerry.huihome.module.home.adapter.PageAdapterListener;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GuideActivity extends AppCompatActivity{
    private boolean isFirstRun = true;
    @BindView(R.id.vp_guide)
    protected ViewPager vpGuide;
    @BindView(R.id.rb_guide)
    protected RadioGroup rpGuide;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        isFirstRun = isFirstRun();
        if(isFirstRun){
            setContentView(R.layout.activity_guide);
            ButterKnife.bind(this);
            initViews();
        }else{
            setContentView(R.layout.activity_welcome_activity);
            initGoHome();
        }
    }


    private void initGoHome(){
        handler.sendEmptyMessageDelayed(1,2*1000);
    }


    private int[] mInds = {R.drawable.guide_one, R.drawable.guide_2, R.drawable.guide_three};

    protected void initViews(){
        GuidePageAdapter guiAdapter = new GuidePageAdapter(GuideActivity.this, mInds);
        vpGuide.setAdapter(guiAdapter);
        vpGuide.addOnPageChangeListener(new PageAdapterListener(){
            @Override
            public void onPageSelected(int position){
                View view = rpGuide.getChildAt(position);
                rpGuide.check(view.getId());
            }
        });
        vpGuide.setCurrentItem(0);
        rpGuide.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId){
                int count = group.getChildCount();
                for(int i = 0; i < count; i++){
                    if(group.getChildAt(i).getId() == checkedId){
                        vpGuide.setCurrentItem(i);
                        break;
                    }
                }
            }
        });
    }
    private boolean isFirstRun(){
        SharedPreferences sp = getSharedPreferences("drawHouse", MODE_PRIVATE);
        return sp.getBoolean("isFirstRun", true);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            Intent intent = new Intent(GuideActivity.this,MainActivity.class);
            startActivity(intent);
            finish();
        }
    };

    @Override
    protected void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}
